import debugCallBacks
from whiff import resolver
from whiff import whiffenv
from whiff.rdjson import jsonParse
from whiff.middleware import callTemplate

def erdDetach(env, start_response):
    env = resolver.process_cgi(env, parse_cgi=True)
    entityName = whiffenv.cgiGet(env, "entityName")
    relName = whiffenv.cgiGet(env, "relName")
    #pr "detaching", (entityName, relName)
    rule = whiffenv.cgiGet(env, "Rule")
    rule = resolver.unquote(rule)
    (flag, rulevalue, cursor) = jsonParse.parseValue(rule)
    if not flag:
        raise ValueError, "failed to parse rule "+repr(rule)
    #start_response('200 OK', [('Content-Type', 'application/javascript')])
    #yield "alert('trying to delete element %s');" % name
    #yield "alert('rule is %s');" % rule.replace("\n", " ")
    # remove all participation of entity in relationship
    newrule = []
    for x in rulevalue:
        if x[0]=="participate" and x[1]==entityName and x[2]==relName:
            #pr "ignoring", rule
            pass # ignore this participation
        else:
            #pr "appending", rule
            newrule.append(x)
    # put new rule in cgi dict
    env = env.copy()
    newrulestr = jsonParse.format(newrule)
    #pr "new rule is"
    #pr newrulestr
    resolver.override_cgi_require(env, "Rule", newrulestr)
    # deliver the javascript
    #pr "NOW CALLING ERDTEST"
    app = callTemplate.callTemplate("erdTest.js")
    return app(env, start_response)

__wsgi__ = erdDetach
